﻿using HttpForwardServer.Log;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace HttpForwardServer
{
    public class Startup
    {
        private bool runFlag = false;
        public void Start()
        {
            string listenerUrl = ConfigurationManager.AppSettings["listenerUrl"]?.ToString();

            HttpListener httpListener = new HttpListener();
            httpListener.Prefixes.Add(listenerUrl);
            httpListener.Start();
            runFlag = true;
            ShowInfo($"监听已启动，地址：{listenerUrl}");

            Task.Factory.StartNew(async () =>
            {
                do
                {
                    ShowInfo($"等待请求");
                    HttpListenerContext context = await httpListener.GetContextAsync();
                    ShowInfo($"接收请求");
                    HttpListenerRequest request = context.Request;
                    HttpListenerResponse response = context.Response;

                    string traceUrl = $"http://localhost:8765{request.Url.PathAndQuery}";
                    string responseContentType = "text/html;charset=UTF-8";
                    string httpMethod = request.HttpMethod.ToUpper();

                    try
                    {
                        string responseData = string.Empty;
                        if (httpMethod.Equals("GET"))
                        {
                            responseData = HttpMethods.GetRaw(traceUrl, null);
                            responseContentType = "text/html;charset=UTF-8";
                            ShowInfo($"请求方式[{httpMethod}],请求地址[{traceUrl}],响应参数[{responseData}]");
                        }
                        else if (httpMethod.Equals("POST"))
                        {
                            StreamReader sw = new StreamReader(request.InputStream);
                            string requestData = sw.ReadToEnd();
                            sw.Close();
                            if (string.IsNullOrEmpty(requestData))
                            {
                                ShowInfo($"无请求数据");
                            }
                            responseData = HttpMethods.PostRaw(traceUrl, requestData, 10000);
                            responseContentType = "application/json";
                            ShowInfo($"请求方式[{httpMethod}],请求地址[{traceUrl}],请求参数[{requestData}],响应参数[{responseData}]");
                        }
                        else
                        {
                            responseData = $"请求方式[{httpMethod}],请求地址[{request.Url.ToString()}]未处理,不支持的请求方式";
                            ShowInfo(responseData);
                        }
                        byte[] responseBytes = Encoding.UTF8.GetBytes(responseData);
                        response.ContentLength64 = responseBytes.Length;
                        response.ContentType = responseContentType;
                        await response.OutputStream.WriteAsync(responseBytes, 0, responseBytes.Length);
                        response.Close();
                        ShowInfo($"请求结束");
                    }
                    catch (Exception ex)
                    {
                        ShowInfo($"请求方式[{httpMethod}],请求地址[{traceUrl}],请求出错[{ex.Message}]");
                        Logger.LOG_ERROR.Error(ex);

                        string responseData = ex.Message + ex.StackTrace;
                        byte[] responseBytes = Encoding.UTF8.GetBytes(responseData);
                        response.ContentLength64 = responseBytes.Length;
                        response.ContentType = responseContentType;
                        await response.OutputStream.WriteAsync(responseBytes, 0, responseBytes.Length);
                        response.Close();
                    }
                } while (runFlag);
            });

            ShowInfo($"服务启动");
        }

        public void Stop()
        {
            runFlag = false;
            ShowInfo($"服务停止");
        }

        private void ShowInfo(string msg)
        {
            string showMsg = $"[{DateTime.Now.ToString("HH:mm:ss")}]{msg}";
            Console.WriteLine(showMsg);
#if DEBUG
            Logger.LOG_INFO.Info(showMsg);
#endif
        }
    }
}
